package im.yisme.view.ui.util;

import im.yisme.view.ui.component.YButton;

import java.util.ArrayList;
import java.util.Iterator;

import android.util.Log;
import android.view.MotionEvent;

public class ButtonEventListener{

	private ArrayList<YButton> registeredButton;
	private boolean isCaught;
	private YButton selectedButton;
	
	public ButtonEventListener(){
		registeredButton=new ArrayList<YButton>();
	}
    public boolean onButtonEvent(MotionEvent event){
		
    	
		Iterator<YButton> it=registeredButton.iterator();
		
		if(!isCaught && event.getAction() != MotionEvent.ACTION_DOWN) return false;
		
		
		
		while (it.hasNext()) {
			YButton yButton =  it.next();
			if(!yButton.isVisible()) continue;
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					 isCaught=false;
					 if(yButton.isTouched(event.getX(), event.getY())){
						 yButton.press();
						 isCaught=true;
						 selectedButton=yButton;
					 }
					 if(isCaught) return true;
					 break;
				case MotionEvent.ACTION_MOVE:
					 if(!yButton.isTouched(event.getX(), event.getY())){
						 yButton.release();
					 }
						
					 else if(yButton.equals(selectedButton)){
						 yButton.press();
					 }
						
					 break;
				case MotionEvent.ACTION_UP:
					 if(yButton.isTouched(event.getX(), event.getY()) && yButton.equals(selectedButton)){
						 yButton.click();
					 }
						
					 yButton.release();
					 break;
				default:
					break;
				}
			
		}
		
		return isCaught;
	}
    
    public void registerButton(YButton button){
    	registeredButton.add(button);
    }
}
